<template>
  <basic-dialog
    v-model:open="toggle"
    title="Create Battle"
    width="57.5rem"
    class="_create-battle-model"
    lock-scroll
    :fullscreen="isMobile"
    :z-index="isMobile ? 998 : 2000"
    :sticky-header="isMobile"
    @open="onOpen"
    @closed="onClosed"
  >
    <div class="_create-battle-wrapper" :class="{ _mobile: isMobile }">
      <div class="_form-list">
        <div class="_form-item">
          <div>
            <label class="_text-middle">Choose number of players</label>
          </div>
          <div class="_player-list _text-middle">
            <div
              class="_player-item _select-item _click"
              :class="{ _active: form.play_type === play.value }"
              v-for="play in players"
              :key="play.value"
              @click="form.play_type = play.value"
            >
              <div class="_player-dot" v-for="item in play.length" :key="item">
                <div>1</div>
                <img
                  class="_active-icon"
                  v-if="item !== play.length"
                  :src="BatteCreateWhite"
                />
                <img
                  class="_unactive-icon"
                  v-if="item !== play.length"
                  :src="BattleIcon"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="_form-item">
          <div>
            <label class="_text-middle">Battle Mode</label>
          </div>
          <div class="_mode-list">
            <div
              class="_mode-item _select-item _click"
              :class="{ _active: form.mode === mode.value }"
              v-for="mode in modes"
              :key="mode.value"
              @click="form.mode = mode.value"
            >
              <div class="_icon-wrapper">
                <img
                  :src="form.mode === mode.value ? mode.activeIcon : mode.icon"
                />
              </div>
              <div class="_model-info">
                <div class="_text-middle">{{ mode.label }}</div>
                <div class="_text-small text-hex-9D9D9D">{{ mode.desc }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="_form-item">
          <div class="_form-title-space">
            <label class="_text-middle">
              Selected packs（{{ currentBox.length }}）
            </label>
            <el-button
              size="large"
              type="info"
              :disabled="loading"
              @click="onSelectPack"
            >
              <div class="_button-text _text-middle">
                <img :src="Add" />
                <span>Add Boxs</span>
              </div>
            </el-button>
          </div>
          <div class="_box-list">
            <box-container
              class="_box-item"
              v-for="box in currentBox"
              :key="box.id"
            >
              <div
                class="flex flex-col items-center justify-between gap-1rem h-full w-full"
              >
                <div class="flex-1 h-0 w-full">
                  <img
                    class="h-full w-full"
                    style="object-fit: fill"
                    :src="box?.image"
                  />
                </div>
                <div class="_box-bottom" @click.stop>
                  <price-btn
                    :price="Number(box?.spin_amount || 0)"
                    :price-class="{
                      '!text-0.75rem !rounded-0.25rem': isMobile,
                    }"
                  >
                    <span class="text-primary"> *{{ box.num }}</span>
                  </price-btn>
                </div>
              </div>
            </box-container>
          </div>
        </div>
      </div>

      <div ref="btnRef" class="_btn-wrapper">
        <el-button
          class="_btn"
          size="large"
          type="primary"
          :disabled="form.boxs.length === 0"
          :loading="loading"
          @click="onCreateBattle"
        >
          <div class="_text-middle text-hex-1D1F20">
            Create battle for ${{ totalUsd }}
          </div>
        </el-button>
      </div>

      <div
        v-if="isMobile"
        :style="{
          height: `${btnRef?.getBoundingClientRect?.().height || 0}px`,
        }"
      ></div>
    </div>
  </basic-dialog>

  <select-pack
    v-model:open="selectPackInfo.toggle"
    v-model:selected-box="form.boxs"
  />
</template>

<script lang="tsx" setup>
import { createBattle } from "@/api/battles";
import { onBuriedPoint } from "@/api/user";
import Add from "@/assets/add.png";
import BattleIcon from "@/assets/battle.png";
import BatteCreateWhite from "@/assets/battle-create-white.png";
import BasicDialog from "@/components/BasicDialog/basicDialog.vue";
import BoxContainer from "@/components/BoxContainer/box-container.vue";
import { useMedia } from "@/hooks/useMedia";
import { useModalToggle } from "@/hooks/useModalToggle";

import {
  createBattleEmits,
  createBattleProps,
  EnumBattleMode,
  EnumBattlePlayType,
  modes,
  players,
} from "./createBattle";
import type { SelectBoxItem } from "./SelectPack/selectPack";
import SelectPack from "./SelectPack/selectPack.vue";

const props = defineProps(createBattleProps);
const emits = defineEmits(createBattleEmits);

const route = useRoute();
const router = useRouter();
const isMobile = useMedia();
const { modalToggleInfo: selectPackInfo, onOpenModal: onOpenPack } =
  useModalToggle();

const btnRef = ref<HTMLDivElement>();
const loading = ref(false);
const form = ref<API.Battles.CreateBattleParams & { boxs: SelectBoxItem[] }>({
  play_type: EnumBattlePlayType.TowPlayer,
  mode: EnumBattleMode.NormalMode,
  boxs: [],
});

const currentBox = computed(() => {
  return form.value.boxs.filter((item) => item.num && item.num > 0);
});

const toggle = computed({
  get() {
    return props.open;
  },
  set(isOpen: boolean) {
    emits("update:open", isOpen);
  },
});

const totalUsd = computed(() => {
  return form.value.boxs.reduce((total, item) => {
    return (total * 100 + Number(item.spin_amount) * 100 * item.num) / 100;
  }, 0);
});

function onClosed() {
  form.value = {
    play_type: EnumBattlePlayType.TowPlayer,
    mode: EnumBattleMode.NormalMode,
    boxs: [],
  };
}

function onSelectPack() {
  onOpenPack();
  onBuriedPoint({
    page_name: "创建battle弹窗",
    action: "点击按钮",
    button_name: "add-packs",
    ...(route.params || {}),
    ...(route.query || {}),
  });
}

// 创建battle
async function onCreateBattle() {
  loading.value = true;
  const result = await createBattle({
    mode: form.value.mode,
    play_type: form.value.play_type,
    box_ids: currentBox.value.reduce((arr, item) => {
      return arr.concat(new Array(item.num).fill(item.id));
    }, [] as number[]),
  });
  if (result?.battle_id) {
    if (route.fullPath === "/battles") {
      router.push(`/battles/${result.battle_id}`);
    } else {
      const href = router.resolve(`/battles/${result.battle_id}`);
      window.open(href.href, "_self");
    }
  }
  loading.value = false;
  onBuriedPoint({
    page_name: "创建battle弹窗",
    action: "点击按钮",
    button_name: "create-battle",
    json: currentBox.value
      .reduce((arr, item) => {
        return [...arr, `${item.id}-${item.num}`];
      }, [] as string[])
      .join("|"),
  });
}

function onOpen() {
  onBuriedPoint({
    page_name: route.meta?.name as string,
    action: "点击按钮",
    button_name: "create-bottom",
    ...(route.params || {}),
    ...(route.query || {}),
  });
}
</script>

<style lang="less" scoped>
._create-battle-wrapper {
  color: #fff;
  padding: 2rem 0 2rem;
  ._form-list {
    @apply flex flex-col;
    gap: 1.88rem;
    margin-bottom: 3.06rem;
    ._form-item {
      @apply flex flex-col;
      gap: 1.25rem;

      ._form-title-space {
        @apply flex items-center justify-between;
        ._button-text {
          @apply flex items-center;
          gap: 0.5rem;
          img {
            width: 1.25rem;
          }
        }
      }

      ._player-list,
      ._player-item,
      ._player-dot,
      ._mode-list,
      ._mode-item {
        @apply flex items-center;
      }

      ._select-item {
        border-radius: var(--el-border-radius-base);
        border: 0.06rem solid #464a4b;
        &._active {
          background: rgba(63, 211, 203, 0.15);
          border-color: var(--el-color-primary);
        }
      }

      ._player-list {
        gap: 2.5rem;
        ._player-item {
          gap: 1rem;
          padding: 0 2.44rem;
          height: 2.5rem;
          &._active {
            img {
              &._active-icon {
                display: block !important;
              }

              &._unactive-icon {
                display: none !important;
              }
            }
          }
          ._player-dot {
            gap: 1rem;
            img {
              display: none;
              width: 1.06rem;
              object-fit: contain;
              &._unactive-icon {
                display: block;
              }
            }
          }
        }
      }

      ._mode-list {
        gap: 0.63rem;
        ._mode-item {
          @apply flex-1 w-0;
          gap: 1.19rem;
          padding: 1rem 2rem;
          height: 5.44rem;
          ._icon-wrapper {
            width: 4rem;
            height: 100%;
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
          }
          ._model-info {
            @apply flex flex-col;
            gap: 0.5rem;
          }
        }
      }

      ._box-list {
        @apply flex flex-wrap;
        gap: 0.63rem;
        ._box-item {
          @apply select-none;
          aspect-ratio: 10.89 / 20.06;
          min-height: 0;
          width: calc((100% - 0.63rem * 4) / 5);
          background-color: #373a3b;
        }
      }
    }
  }

  ._btn-wrapper {
    padding: 0 7.19rem;
    ._btn {
      @apply w-full;
    }
  }

  &._mobile {
    padding: 0;
    ._form-list {
      padding: 0.94rem 1.13rem 1.13rem;
      margin: 0;
      ._form-item {
        ._player-list {
          @apply flex-wrap;
          gap: 0.94rem;
          ._player-item {
            padding: 0 1.81rem;
          }
        }

        ._mode-list {
          @apply flex-col w-full;
          gap: 1.25rem;
          ._mode-item {
            @apply w-full;
          }
        }

        ._box-list {
          @apply flex flex-wrap;
          gap: 1.19rem;
          ._box-item {
            width: calc((100% - (1.19rem * 2)) / 3);
          }
        }
      }
    }

    ._btn-wrapper {
      @apply fixed left-0 right-0 bottom-0 w-full;
      padding: 0.94rem 1.13rem;
      background-color: #232829;
    }
  }
}
</style>
